package api

import (
	"ams/global"
	"fmt"
	"github.com/gin-gonic/gin"
	"lib/middleware"
	"path/filepath"
)

func StartHttpServer(apiPrefix string) (err error) {
	app := gin.New()
	staticGroup := app.Group(fmt.Sprintf("%s/static/", apiPrefix))
	staticRouter(staticGroup) // 静态资源组

	aipGroup := app.Group(apiPrefix)
	aipGroup.Use(middleware.HttpLog())
	wsRouter(aipGroup)     // ws的路由组
	clientRouter(aipGroup) // 客户端的路由组
	policyRouter(aipGroup) // 策略路由组
	pluginRouter(aipGroup) // 插件路由组
	assetRouter(aipGroup)  // 资产管理路由组
	aiRouter(aipGroup)     // ai 调用
	err = app.Run(global.Conf.Http.Addr)
	return err
}

func staticRouter(r *gin.RouterGroup) {
	r.Static("/plugin", filepath.Join(global.Conf.AppFolder, "plugin"))
	r.Static("/orderPic", filepath.Join(global.Conf.AppFolder, "orderPic"))
}

func wsRouter(r *gin.RouterGroup) {
	sub := r.Group("ws")
	sub.GET("chat", ChatApi.Conn)
}

func aiRouter(r *gin.RouterGroup) {
	sub := r.Group("ai")
	sub.POST("test", AiApi.CallTestHttp)
	sub.GET("wstest", AiApi.CallTestWS)
}

func clientRouter(r *gin.RouterGroup) {
	sub := r.Group("client")
	sub.Use(middleware.GinAuthorizationMiddleAware())
	sub.GET("page", ClientApi.Page)
	sub.GET("list", ClientApi.List)
	sub.GET("LogDetail", ClientApi.LogDetail)
}

func policyRouter(r *gin.RouterGroup) {
	sub := r.Group("policy")
	sub.Use(middleware.GinAuthorizationMiddleAware())
	sub.GET("list", PolicyApi.List)
	sub.POST("add", PolicyApi.Add) // 策略的增、删、改 只影响下一次的客户端，需要刷新的策略的请单独调用更新指令
	sub.DELETE("del", PolicyApi.Delete)
	sub.PUT("update", PolicyApi.Update)
}

func pluginRouter(r *gin.RouterGroup) {
	sub := r.Group("plugin")
	sub.Use(middleware.GinAuthorizationMiddleAware())

	sub.GET("list", PluginApi.List)
	sub.POST("add", PluginApi.Add)
	sub.DELETE("del", PluginApi.Delete)
	sub.PUT("update", PluginApi.Update)
	sub.POST("file", PluginApi.UploadPlugin)
}

func assetRouter(r *gin.RouterGroup) {
	sub := r.Group("asset")
	sub.Use(middleware.GinAuthorizationMiddleAware())

	sub.GET("listType", AssetApi.TypeList)
	sub.POST("addType", AssetApi.CreateType)
	sub.DELETE("delType", AssetApi.DeleteType)

	sub.GET("categoryList", AssetApi.CategoryList)
	sub.GET("categoryTree", AssetApi.CategoryTree)
	sub.POST("addCategory", AssetApi.CreateCategory)
	sub.DELETE("delCategory", AssetApi.DeleteCategory)

	sub.GET("page", AssetApi.Page)
	sub.POST("add", AssetApi.Add)
	sub.DELETE("del", AssetApi.Del)

	// 耗材
	sub.GET("consPage", AssetApi.AssetConsPage)
	sub.GET("consList", AssetApi.AssetConsList)
	sub.GET("consLogsPage", AssetApi.AssetConsLogsPage)
	sub.POST("consLogsAdd", AssetApi.AssetConsCreateLogs)
	sub.POST("orderPic", AssetApi.UploadOrderPic)
	sub.POST("ocr", AssetApi.CallOCR)
}
